package com.atguigu.gmall.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;

import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

//配置跨域规则
@Configuration
public class CorsConfig {

    //配置配置CorsWebFilter产生CORS过滤器，配置CORS跨域规格则
    @Bean
    public CorsWebFilter corsWebFilter(){
        //配置CORS
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //1.允许访问域名
        corsConfiguration.addAllowedOrigin("*");
        //2.允许访问方式
        corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
        corsConfiguration.addAllowedMethod(HttpMethod.GET);
        corsConfiguration.addAllowedMethod(HttpMethod.PUT);
        corsConfiguration.addAllowedMethod(HttpMethod.POST);
        corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);
        //3.配置允许提交头信息
        corsConfiguration.addAllowedHeader("*");
        //4.允许提交cookie
        corsConfiguration.setAllowCredentials(true);
        //5.配置预检请求有效时间
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //注册CORS配置
        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }

}
